<template>
  <!-- 标题 -->
  <p class="title">{{ pageData.title }}</p>

  <!-- 表格 -->
  <Table ref="tableRef" :search="search" :tools="tools" :columns="columns" :api="getThingInfo" />

  <!-- 增加模态框 -->
  <n-modal v-model:show="pageData.isShowAddModel" :mask-closable="false" preset="dialog" title="增加" positive-text="确定"
    negative-text="取消" style="width: 600px" @positive-click="add" @negative-click="addCancel"
    @after-leave="closeAddModel">
    <Form :config="addFormConfig" ref="addFormRef" />
    <div class="img-box">
      <p class="name">图片 <span>*</span></p>
      <div class="img" @click="uploadFile">
        <n-image v-if="imageURL" width="95" height="95" :src="imageURL" lazy preview-disabled />
        <div v-else class="icon-box">
          <p class="icon-title">点击上传</p>
          <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
        </div>
      </div>
      <input type="file" name="" id="" class="file-input" accept="image/*" ref="imageInputRef" @change="handleFile" />
    </div>
  </n-modal>

  <!-- 修改模态框 -->
  <n-modal v-model:show="pageData.isShowUpdateModel" :mask-closable="false" preset="dialog" title="编辑"
    positive-text="确定" negative-text="取消" style="width: 600px" @positive-click="update" @negative-click="updateCancel"
    @after-leave="closeUpdateModel">
    <Form ref="updateFormRef" :config="updateFormConfig" />
    <div class="img-box">
      <p class="name">图片 <span>*</span></p>
      <div class="img" @click="updateUploadFile">
        <n-image v-if="updateImageURL" width="95" height="95" :src="updateImageURL" lazy preview-disabled />
        <div v-else class="icon-box">
          <p class="icon-title">点击上传</p>
          <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
        </div>
      </div>
      <input type="file" name="" id="" class="file-input" accept="image/*" ref="updateImageInputRef"
        @change="handleUpdateFile" />
    </div>
  </n-modal>

</template>

<script setup lang="ts">
import { getThingType } from '@/api/thing/thingType';
import { getThingInfo, addThingInfo, updateThingInfo, removeThingInfo } from '@/api/thing/thingInfo'
import { NButton, NSpace } from 'naive-ui';
import { h, reactive, ref } from 'vue';
import { addFormConfig, updateFormConfig } from './config'
import { useRoute } from 'vue-router'
import uploadIcon from "@/assets/icons/upload.png";
import { deepClone } from '@/utils/lib/clone';
import { getAllUser } from '@/api/system/user';
import getBASE64 from '@/utils/lib/upload'
import { formatDate } from '@/utils/lib/date';
import { status } from "@/enums/thingEnum";

export interface IDataSource {
  tools: Record<string, any>[]
  data: Record<string, any>[]
  columns: Record<string, any>[]
  loading: boolean
  pageData: Record<string, any>[]
}

const addFormRef = ref()
const updateFormRef = ref()
const imageInputRef = ref()
const updateImageInputRef = ref()
const tableRef = ref()

const imageURL = ref<string>('')
const updateImageURL = ref<string>('')


const route = useRoute()

const closeUpdateModel = () => {
  pageData.isShowUpdateModel = false
}

const closeAddModel = () => {
  pageData.isShowAddModel = false
}
/**
 * 点击触发file事件
 */
const uploadFile = () => {
  imageInputRef.value.click()
}

const updateUploadFile = () => {
  updateImageInputRef.value.click()
}
/**
 * 上传图片
 * @param e 事件对象
 */
const handleFile = async (e) => {
  try {
    const file = e.target.files[0]
    if (!file) {
      return
    }
    const BASE64 = await getBASE64(file);
    imageURL.value = BASE64 as string;
  } catch (error) {
    return Promise.reject(error)
  }
}

const handleUpdateFile = async (e) => {
  try {
    const file = e.target.files[0]
    if (!file) {
      return
    }
    const BASE64 = await getBASE64(file);
    updateImageURL.value = BASE64 as string;
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 增加启事
 */
const add = async () => {
  try {
    const instance = addFormRef.value.getFormRef()
    console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = {
          ...instance.model,
          TIME: formatDate(new Date()),
          is_delete: 0,
          audit_status: '已审核',
          status_id: status[instance.model.tag === "寻物启事" ? "正在寻找" : "等待认领"],
          img: imageURL.value
        }
        if (data.img === "") {
          window['$message'].warning("请上传图片");
          return;
        }
        await addThingInfo(data)
        tableRef.value.getData()
        imageURL.value = ''
      } else {
        window['$message'].error('增加启事失败')
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 更新启事信息
 */
const update = async () => {
  try {
    const instance = updateFormRef.value.getFormRef()
    // console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = {
          ...instance.model,
          id: pageData.selectedRow.id,
          img: updateImageURL.value
        }
        data.look_count = Number(data.look_count)
        data.is_delete = data.is_delete === '是' ? 1 : 0
        data.TIME = formatDate(new Date(data.TIME)).slice(0, 10) + ' ' + formatDate(new Date(data.public_time)).slice(-8)
        delete data.public_time
        console.log(data);

        await updateThingInfo(data)
        tableRef.value.getData()
      } else {
        window['$message'].error('修改启事失败')
      }
    })


  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 增加弹窗取消
 */
const addCancel = () => {
  pageData.isShowAddModel = false
}


/**
 * 更新弹窗取消
 */
const updateCancel = () => {
  pageData.isShowUpdateModel = false
}

const addInfo = (val) => {
  console.log('add', val);
  pageData.isShowAddModel = true

  // 给增加表单增加配置
  addFormConfig.formItems.forEach(item => {
    if (item.field === 'user_id') {
      item.options = pageData.users.map(item => {
        return {
          label: item.user_id,
          value: item.user_id
        }
      })
    }
    if (item.field === 'type_id') {
      item.options = pageData.types.map(item => {
        return {
          label: item.TYPE,
          value: item.id,
        }
      })
    }
  })
}

const editInfo = (row) => {
  console.log('edit', row);
  pageData.selectedRow = deepClone(row)
  updateImageURL.value = pageData.selectedRow.img
  pageData.isShowUpdateModel = true
  updateFormConfig.formItems.forEach(item => {
    if (item.field === 'user_id') {
      item.value = row.user_id
      item.options = pageData.users.map(item => {
        return {
          label: item.user_id,
          value: item.user_id
        }
      })
    }
    if (item.field === 'title') {
      item.value = row.title
    }
    if (item.field === 'location') {
      item.value = row.location
    }
    if (item.field === 'look_count') {

      item.value = row.look_count.toString()
    }
    if (item.field === 'tag') {
      item.value = row.tag
    }
    if (item.field === 'audit_status') {
      item.value = row.audit_status
    }
    if (item.field === 'content') {
      item.value = row.content
    }
    if (item.field === 'TIME') {
      item.value = new Date(row.TIME.slice(0, 10)).getTime()
    }
    if (item.field === 'public_time') {
      item.value = new Date(row.TIME.slice(-8)).getTime()
    }
    if (item.field === 'status_id') {
      item.value = row.status_id
    }
    if (item.field === 'is_delete') {
      item.value = row.is_delete
    }
  })
}

/**
 * 删除启事信息
 */
const deleteInfo = async (row) => {

  try {
    console.log('delete', row);
    window['$dialog'].success({
      title: '删除',
      content: '是否删除该条数据？',
      maskClosable: false,
      negativeText: '取消',
      positiveText: '确定',
      onPositiveClick: async () => {
        if (row.is_delete === '是') {
          window['$message'].warning('该项已删除')
          return
        }
        await removeThingInfo({
          id: row.id
        })
        tableRef.value.getData()
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 搜索栏
 */
const search = [
  {
    name: '关键字搜索',
    type: 'input',
    prop: 'key',
  },
  {
    name: '审核状态',
    type: 'select',
    prop: 'status',
    options: [
      {
        label: "未审核",
        value: "未审核",
      },
      {
        label: "已审核",
        value: "已审核",
      }
    ]
  },
  {
    name: '标签',
    type: 'select',
    prop: 'tag',
    options: [
      {
        label: "认领启事",
        value: "认领启事",
      },
      {
        label: "寻物启事",
        value: "寻物启事",
      }
    ]
  },
  {
    name: '时间',
    type: 'date',
    prop: 'TIME',
  }
]

/**
 * 工具栏按钮
 */
const tools = [
  {
    name: '新增启事',
    type: 'error',
    handleClick: addInfo
  }
]

/**
 * 表格
 */
const columns = [
  {
    title: '发布者',
    key: 'user_id',
    width: 80,
  },
  {
    title: '标签',
    key: 'tag',
    width: 80,
  },
  {
    title: '标题',
    key: 'title',
    width: 120,
    ellipsis: true
  },
  {
    title: '内容',
    key: 'content',
    ellipsis: true,
    width: 200,
  },
  {
    title: '地点',
    key: 'location',
    width: 100,
  },
  {
    title: '发布时间',
    key: 'TIME',
    width: 200,
  },
  {
    title: '查看人数',
    key: 'look_count',
    width: 100,
  },
  {
    title: '审核状态',
    key: 'audit_status',
    width: 120,
  },
  {
    title: '是否删除',
    key: 'is_delete',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      return h(NSpace, null, [
        h(NButton, {
          type: 'info',
          size: 'small',
          onClick: () => editInfo(row)
        }, () => '编辑'),
        h(NButton, {
          type: 'error',
          size: 'small',
          onClick: () => deleteInfo(row)
        }, () => '删除')
      ])
    }
  }
]


const pageData = reactive({
  selectedRow: {} as any,
  isShowAddModel: false as boolean,
  isShowUpdateModel: false as boolean,
  title: route.meta.title as string,
  users: [] as any,
  types: [] as any,
})

/**
 * 获取所有用户
 */
const getUser = async () => {
  try {
    const res = await getAllUser()
    if (res.data.code === 200) {
      pageData.users = res.data.data.filter(item => !item.is_admin)
    } 
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取所有类型
 */
const getType = async () => {
  try {
    const res = await getThingType({
      pageNo: 1,
      pageSize: 5
    })
    if (res.data.code === 200) {
      pageData.types = res.data.data.result
    }
  } catch (error) {
    return Promise.reject(error)
  }
}


getUser()
getType()


</script>

<style scoped lang="less">
@import '@/styles/mixin.less';

.title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.img-box {
  .flex(row, flex-start, center);
  padding-left: 30px;

  .name {
    span {
      color: #d03050;
    }
  }

  .img {
    // margin-top: 10px;
    margin-left: 10px;
    width: 100px;
    height: 100px;
    border: 2px dotted #ccc;
    background-color: rgb(250, 250, 252);
    .flex(row, center, center);
    cursor: pointer;

    p {
      font-size: 20px;
    }

    &:hover {
      border: 2px dotted green;
    }

    .icon-box {
      .flex(column, center, center);

      .icon-title {
        font-size: 14px;
        color: #666;
      }
    }
  }

  .file-input {
    display: none;
  }
}
</style>